#include "processing.h"


#include "ARToolKitPlus/TrackerSingleMarkerImpl.h"
#include <iostream>
using namespace std;


static const char * camera_file = "../data/artp-unibrainwide21.txt";


class MyLogger : public ARToolKitPlus::Logger
{
	void artLog(const char* nStr)
	{
		printf(nStr);
	}
};

MyLogger      logger;


Processing* Processing::create(int w,int h)
{
	Processing* proc = new Processing();
	if (proc->initArtkplus(w,h))
	{
		return proc;
	}
	delete proc;
	return NULL;
}

Processing::~Processing()
{
	if (_artkptracker != NULL)
	{
		delete _artkptracker;
	}	
}



bool Processing::initArtkplus(int widthImage,int heightImage )
{

	const bool    useBCH = true;


	_artkptracker = new ARToolKitPlus::TrackerSingleMarkerImpl<6,6,6, 1, 8>(widthImage,heightImage);
	_artkptracker->setLogger(&logger);
	_artkptracker->setPixelFormat(ARToolKitPlus::PIXEL_FORMAT_BGR);
	if(!_artkptracker->init(camera_file, 0.001f, 1000.0f))            // load std. ARToolKit camera file		
	{
		printf("ERROR: init() failed\n");

		delete _artkptracker;
		return false;
	}

	// define size of the marker
	_artkptracker->setPatternWidth(0.01);//dummy

	// the marker in the BCH test image has a thin border...
	_artkptracker->setBorderWidth( useBCH ? 0.125f : 0.250f );

	// set a threshold. alternatively we could also activate automatic thresholding
	_artkptracker->setThreshold(150);
	_artkptracker->activateAutoThreshold(true);

	// let's use lookup-table undistortion for high-speed
	// note: LUT only works with images up to 1024x1024
	_artkptracker->setUndistortionMode(ARToolKitPlus::UNDIST_LUT);//UNDIST_NONE

	_artkptracker->setMarkerMode(useBCH ? ARToolKitPlus::MARKER_ID_BCH : ARToolKitPlus::MARKER_ID_SIMPLE );



	return true;


}

bool Processing::tryArtkp(const unsigned char* image,float widthMarker)
{	
	ARToolKitPlus::ARMarkerInfo * makersInfo;
	int markerId = _artkptracker->calc(image,-1,false,&makersInfo,&_numMarkers);
	if (markerId >= 0)
	{
		cout << markerId << endl ;
		ARFloat center[] = {0,0};
		_artkptracker->calcOpenGLMatrixFromMarker(makersInfo,center,widthMarker,_last_glModelView);
		return true;		
	}		
	return false;

}

double* Processing::getGLProjectionMatrix() const
{
	if (_artkptracker)
	{
		return (double*)(_artkptracker->getProjectionMatrix());
	}
	return NULL;
}

void Processing::process( IplImage* _image)
{

	tryArtkp((unsigned char *)_image->imageData,0.08f);

}

double* Processing::getGLModelViewMatrix() const
{
	if (_artkptracker)
	{
		return (double*)(_last_glModelView);
	}
	return NULL;
}